package com.whately.core.base.fileupload.qiniu.util;

import com.whately.core.base.utils.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 图像上传辅助
 */
public class ImagesHelper {
	private static final Logger logger = LoggerFactory.getLogger(ImagesHelper.class);

	/**
	 * 场景：前台传的是图片绝对路径，数据库存储需要图片相对路径 获取图片相对路径
     * http://49.232.15.169:80/fs/resourceFile/corpCert/local/00/2019/12/14/16/219c9db2c4f298b0116cc752421515a736.jpeg?version=1576313258171&e=1576316858&token=WGFwLv7swzRd9O9ZfAwSu9ypje2DzXWniok4m79N:iL74Vw_n6CRZ1L5KfEIX06vpnD4=
	 * or https://
	 */
	public static String getRelativeUrlWithBucketFromAbsPath(String fileName, String bucket) {
		if (StringUtils.isEmpty(fileName) || fileName.indexOf(bucket)<=0) {
			logger.warn("getImageRelativeUrl fail, fileName is null or file name {} not index of bucket {}",fileName,bucket);
			return null;
		}

		//必须以http或者https开头
		if (!fileName.toLowerCase().startsWith("http")) {
			logger.warn("getImageRelativeUrl fail, invalid param[file:{}, bucket:{}].", fileName, bucket);
			return "";
		}

		logger.info("getImageRelativeUrl by fileName[{}] bucket[{}].", fileName, bucket);

		String subFileName = fileName.substring(fileName.indexOf(bucket));
        //去掉?后面的数据 ：因为？后面有可能含有七牛私有空间加密数据
        //重新添加version
        int paramIndex = subFileName.indexOf("?");
        if(paramIndex>0){
            String last = subFileName.substring(paramIndex+1);
            if(StringUtils.isNotBlank(last)&&last.indexOf("token=")>0){
                String[] paramArray = last.split("&");
                String v= StringUtils.EMPTY;
                for(String p:paramArray){
                    if(p.indexOf("version=")==0){
                        v = "?"+p;
                        break;
                    }
                }
                String pre = subFileName.substring(0,paramIndex);
                subFileName = pre + v;
            }


        }
		return subFileName;
	}

	public static String appendVersionToRelationUrlInfo(String path){

		StringBuffer appendParam=new StringBuffer();
		if(StringUtils.isNotBlank(path)&&path.indexOf("version=")<0){
			appendParam.append("version="+ DateUtil.nowMilliSecond());
		}
		if(appendParam.length()>0){
			path += ("?"+appendParam.toString());
		}

		return path;
	}

	public static String appendVersionToRelationUrlInfo(ImageInfoVo imageInfoVo){
		return appendVersionToRelationUrlInfo(imageInfoVo.fetchRelativePath());
	}

}
